<template>
  <move-dialog
    :visible="show"
    :before-close="closeDialog"
    :close-on-click-modal="false"
    width="480px"
    title="新建客户信息"
  >
    <el-form :model="form" :rules="rules" label-position="top" ref="formRef">
      <el-form-item prop="glField" label="选择全局字段">
        <el-select-v2
          v-model="form.glField"
          filterable
          clearable
          :options="allFields"
          style="width: 100%"
          :disabled="type === 'edit'"
          placeholder="请选择"
        ></el-select-v2>
      </el-form-item>
      <el-form-item label="字段规则" prop="oplog">
        <el-checkbox v-model="form.oplog" :disabled="form.glField === 'attachments'">操作日志</el-checkbox>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button link @click="cancel">取消</el-button>
      <el-button type="primary" color="var(--mc-main-color)" @click="save">确定</el-button>
    </template>
  </move-dialog>
</template>

<script lang="ts">
import { computed, defineComponent, getCurrentInstance, reactive, toRefs } from 'vue'
import moveDialog from '@/common/components/move-dialog/index.vue'
import { useRouter } from 'vue-router'
import { addField, updateField } from '@app/customer/apis/info'
import { ElMessage } from 'element-plus'
import { commonStore } from '@/common/store/modules/common'
import mcCache from '@/common/utils/mc-get-cache'
const defaultForm = {
  glField: '',
  oplog: false,
  field: ''
}
export default defineComponent({
  name: 'AddField',
  components: { moveDialog },
  emits: ['onUpdateList'],
  setup(_, { emit }) {
    const state = reactive({
      show: false,
      form: defaultForm,
      rules: {
        glField: [{ required: true, message: '请选择要添加的字段', trigger: 'change' }]
      },
      type: '',
      allDataObj: {} as any
    })

    const $router = useRouter()
    const instance: any = getCurrentInstance()

    // 全局字段
    const globalFields: any = computed(() => {
      return commonStore().publicCache.globalFieldCache || []
    })

    const allFields = computed(() => {
      const choose: any = [
        {
          value: 0,
          label: '预置字段',
          options: []
        },
        {
          value: 1,
          label: '自定义字段',
          options: []
        }
      ]
      if (globalFields.value && globalFields.value.length) {
        globalFields.value.forEach((item: any) => {
          if (item.status && !state.allDataObj[item.field] && state.type === 'add') {
            // 启用的字段&&客户信息列表中不存在的全局字段
            const obj = {
              value: item.field,
              label: item.name
            }
            if (item.category === 'system') {
              choose[0].options.push(obj)
            } else {
              choose[1].options.push(obj)
            }
          } else if (state.type === 'edit') {
            // select回显需全量字段
            const obj = {
              value: item.field,
              label: item.name
            }
            if (item.category === 'system') {
              choose[0].options.push(obj)
            } else {
              choose[1].options.push(obj)
            }
          }
        })
      }
      return choose
    })

    const openDialog = (allDataObj: any, row: any, type: string) => {
      state.show = true
      state.type = type
      state.form = { ...defaultForm, ...row, glField: row.field } // 清空数据
      state.allDataObj = allDataObj
    }

    const closeDialog = () => {
      state.show = false
    }

    const cancel = () => {
      state.show = false
    }

    const save = () => {
      instance?.refs.formRef.validate((valid: boolean) => {
        const { glField, oplog, field } = state.form
        const sendData = {
          glField,
          oplog
        }
        if (valid) {
          ;(state.type === 'add' ? addField(sendData) : updateField({ ...sendData, field })).then((res) => {
            if (res.success) {
              ElMessage.success('操作成功')
              state.show = false
              emit('onUpdateList')
              // 更新pinia
              if (state.type === 'add') {
                mcCache.$addOneCache('cusInfo', res.data, '', 'field') // 新建
              } else {
                mcCache.$updateCache('cusInfo', res.data, 'field', '') // 编辑
              }
            }
          })
        }
      })
    }

    const toPage = () => {
      $router.push('/account/global_field')
    }

    return {
      closeDialog,
      openDialog,
      cancel,
      save,
      toPage,
      allFields,
      ...toRefs(state)
    }
  }
})
</script>

<style lang="stylus" scoped>
.tip {
  color: rgba(0, 0, 0, 0.38);

  .link {
    color: var(--mc-main-color);
    cursor: pointer;
    font-weight: 500;
  }
}
</style>
